package com.sanbi.erp.db.util.easyExcel;

import com.sanbi.erp.core.system.Enums;
import com.sanbi.erp.core.system.ErrorEnum;
import com.sanbi.erp.core.util.Generator;
import com.sanbi.erp.core.util.ProcurementPlanUtils;
import com.sanbi.erp.db.config.BizException;
import com.sanbi.erp.db.dao.ProductMapper;
import com.sanbi.erp.db.domain.*;
import com.sanbi.erp.db.service.*;
import com.sanbi.erp.db.util.CheckoutUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.lang.System;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @introduce: Excel批量导入业务处理
 * @Date: 2022/10/20 21:46
 * @Author: XYP
 */
@Slf4j
@Component
public class EasyExcelService {
    @Resource
    ProductService productService;
    @Resource
    ProductGroupService productGroupService;

    @Resource
    CategoryService categoryService;

    @Resource
    ProviderService providerService;

    @Resource
    StoreService storeService;

    @Resource
    StoreProductService storeProductService;

    @Resource
    ProductMapper productMapper;

    @Resource
    ProcurementPlanService procurementPlanService;

    private static EasyExcelService easyExcelService;

    @PostConstruct
    void init(){easyExcelService=this;}

    /**
     * 批量新增商品(单个商品)
     * @param list
     */
    @Transactional(rollbackFor = Exception.class)
    void insertSelectiveList(List<ProductEasyExcelAdd> list) {
        // 根据对象某个属性进行去重
        List<ProductEasyExcelAdd> productEasyExcelList = list.stream().collect(
                Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(ProductEasyExcelAdd::getProductSku))), ArrayList::new));
        // 校验sku是否存在
        List<String> listSku = new ArrayList<>();
        for (ProductEasyExcelAdd productEasyExcelAdd : productEasyExcelList) {
            listSku.add(productEasyExcelAdd.getProductSku());
        }
        // List<Product> productListSku = easyExcelService.productMapper.selectListBySKU(listSku, listSku.get(CheckoutUtil.TYPE_ZERO));
        if (easyExcelService.productMapper.selectListBySKU(listSku, listSku.get(CheckoutUtil.TYPE_ZERO)).size() > CheckoutUtil.TYPE_ZERO) {
            throw new BizException(ErrorEnum.ErrorCode.authInvalidPassword);
        }
        // 存储批量添加商品的信息
        List<Product> productList = new ArrayList<>();
        // 设置批量添加商品基础信息
        for (ProductEasyExcelAdd productEasyExcel : productEasyExcelList) {
            Product product = new Product();
            product.setProductSku(productEasyExcel.getProductSku());
            product.setProductNameCn(productEasyExcel.getProductNameCn());
            product.setProductNameEn(productEasyExcel.getProductNameEn());
            product.setProductState(productEasyExcel.getProductState());
            product.setProductIsGroup(false);
            product.setLength(productEasyExcel.getLength());
            product.setWidth(productEasyExcel.getWidth());
            product.setHeight(productEasyExcel.getHeight());
            product.setCubageWeight(productEasyExcel.getCubageWeight());
            product.setProductWeight(productEasyExcel.getProductWeight());
            product.setBoxNumber(productEasyExcel.getBoxNumber());
            product.setPurchasePrice(productEasyExcel.getPurchasePrice());
            product.setPictures(productEasyExcel.getPictures());
            product.setProductDesc(productEasyExcel.getProductDesc());
            product.setCustomsClearanceNameCn(productEasyExcel.getCustomsClearanceNameCn());
            product.setCustomsClearanceNameEn(productEasyExcel.getCustomsClearanceNameEn());
            product.setCustomsClearancePrice(productEasyExcel.getCustomsClearancePrice());
            product.setCustomsClearanceWeight(productEasyExcel.getCustomsClearanceWeight());
            product.setCustomsClearanceTexture(productEasyExcel.getCustomsClearanceTexture());
            product.setCustomsClearanceUse(productEasyExcel.getCustomsClearanceUse());
            product.setCustomsClearanceSn(productEasyExcel.getCustomsClearanceSn());
            product.setCustomsClearanceRisky(productEasyExcel.getCustomsClearanceRisky());
            product.setCategoryName(productEasyExcel.getCategoryName()); // 类目名称
            product.setProviderName(productEasyExcel.getProviderName()); // 供应商名称
            product.setAddTime(LocalDateTime.now());
            product.setUpdateTime(LocalDateTime.now());
            product.setDeleted(false);
            productList.add(product);
        }
        // 获取所有的类目
        List<Category> categoryList = easyExcelService.categoryService.selectAllEasyExcel();
        // 获取所有的供应商
        List<Provider> providerList = easyExcelService.providerService.selectAllEasyExcel();
        // 设置类目id
        for (Product product : productList) {
            for (Category category : categoryList) {
                if (product.getCategoryName().equals(category.getNameCn())) {
                    product.setCategoryId(category.getId());
                }
            }
        }
        // 设置供应商id
        for (Product product : productList) {
            for (Provider provider : providerList) {
                if (product.getProviderName().equals(provider.getProviderName())) {
                    product.setProviderId(provider.getId());
                }
            }
        }

        // 批量新增商品
        easyExcelService.productService.insertSelectiveList(productList);

        // 筛查存储到店铺商品表的信息 -->
        // 存储每个商品在那个店铺售卖的相关信息 key:productSku
        Map<String,List<StoreProductEasyExcel>> listMap = new HashMap<>();
        listMap.put("存储每个商品在那个店铺售卖的相关信息",new ArrayList<>());
        // -->
        // 遍历完之后listMap就会是：Map<单个商品的sku,List<多个店铺商品sku>>
        for (ProductEasyExcelAdd productEasyExcel : list) {
            // 判断是否已经存在这个商品项
            for (Map.Entry entry : listMap.entrySet()) {
                if (entry.getKey().equals(productEasyExcel.getProductSku())) {
                    StoreProductEasyExcel storeProductEasyExcel = new StoreProductEasyExcel();
                    storeProductEasyExcel.setStoreName(productEasyExcel.getStoreName());
                    storeProductEasyExcel.setStoreProductSku(productEasyExcel.getStoreProductSku());
                    listMap.get(productEasyExcel.getProductSku()).add(storeProductEasyExcel);
                }
            }
            // 如果循环完没有这个商品就创建这个项
            if (listMap.get(productEasyExcel.getProductSku()) == null) {
                List<StoreProductEasyExcel> storeProductEasyExcels = new ArrayList<>();
                StoreProductEasyExcel storeProductEasyExcel = new StoreProductEasyExcel();
                storeProductEasyExcel.setStoreName(productEasyExcel.getStoreName());
                storeProductEasyExcel.setStoreProductSku(productEasyExcel.getStoreProductSku());
                storeProductEasyExcels.add(storeProductEasyExcel);
                listMap.put(productEasyExcel.getProductSku(), storeProductEasyExcels);
            }
        }
        // -->
        // storeProductSku productId storeId
        List<StoreProduct> storeProductList = new ArrayList<>();
        // 获取所有商品的id和sku
        List<Product> productListAllIdAndSku = easyExcelService.productService.selectListAll();
        // 匹配要添加到店铺商品表的基本信息（存放到集合中）
        for (Product product : productListAllIdAndSku) {
            for (Map.Entry entry : listMap.entrySet()) {
                if (product.getProductSku().equals(entry.getKey())) {
                    List<StoreProductEasyExcel> listOne = (List<StoreProductEasyExcel>)entry.getValue();
                    for (StoreProductEasyExcel storeProductEasyExcel : listOne) {
                        StoreProduct storeProduct = new StoreProduct();
                        storeProduct.setProductId(product.getId());
                        storeProduct.setStoreProductSku(storeProductEasyExcel.getStoreProductSku());
                        storeProduct.setStoreName(storeProductEasyExcel.getStoreName());
                        storeProduct.setAddTime(LocalDateTime.now());
                        storeProduct.setUpdateTime(LocalDateTime.now());
                        storeProduct.setDeleted(false);
                        storeProductList.add(storeProduct);
                    }
                }
            }
        }
        // 获取所有店铺id和名称
        List<Store> storeList = easyExcelService.storeService.selectListAllIdAndName();
        // 设置店铺id
        for (StoreProduct storeProduct : storeProductList) {
            for (Store store : storeList) {
                if (storeProduct.getStoreName().equals(store.getStoreName())) {
                    storeProduct.setStoreId(store.getId());
                }
            }
        }
        // 批量新增店铺商品
        easyExcelService.storeProductService.insertSelectiveList(storeProductList);
    }

    /**
     * 批量新增商品(组合商品)
     * @param list
     */
    @Transactional(rollbackFor = Exception.class)
    void insertSelectiveGroupList(List<ProductEasyExcelGroupAdd> list) {
        // 根据对象某个属性进行去重
        List<ProductEasyExcelGroupAdd> productEasyExcelList = list.stream().collect(
                Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(ProductEasyExcelGroupAdd::getProductSku))), ArrayList::new));
        // 校验sku是否存在
        List<String> listSku = new ArrayList<>();
        for (ProductEasyExcelGroupAdd productEasyExcelAdd : productEasyExcelList) {
            listSku.add(productEasyExcelAdd.getProductSku());
        }
        if (easyExcelService.productMapper.selectListBySKU(listSku, listSku.get(CheckoutUtil.TYPE_ZERO)).size() > CheckoutUtil.TYPE_ZERO) {
            throw new BizException(ErrorEnum.ErrorCode.authInvalidPassword);
        }
        // 存储批量添加商品的信息
        List<Product> productList = new ArrayList<>();
        // 设置批量添加商品基础信息
        for (ProductEasyExcelGroupAdd productEasyExcel : productEasyExcelList) {
            Product product = new Product();
            product.setProductSku(productEasyExcel.getProductSku());
            product.setProductNameCn(productEasyExcel.getProductNameCn());
            product.setProductNameEn(productEasyExcel.getProductNameEn());
            product.setProductState(productEasyExcel.getProductState());
            product.setProductIsGroup(true); // 是否是组合商品标识
            product.setLength(productEasyExcel.getLength());
            product.setWidth(productEasyExcel.getWidth());
            product.setHeight(productEasyExcel.getHeight());
            product.setCubageWeight(productEasyExcel.getCubageWeight());
            product.setProductWeight(productEasyExcel.getProductWeight());
            product.setBoxNumber(productEasyExcel.getBoxNumber());
            product.setPurchasePrice(productEasyExcel.getPurchasePrice());
            product.setPictures(productEasyExcel.getPictures());
            product.setProductDesc(productEasyExcel.getProductDesc());
            product.setCustomsClearanceNameCn(productEasyExcel.getCustomsClearanceNameCn());
            product.setCustomsClearanceNameEn(productEasyExcel.getCustomsClearanceNameEn());
            product.setCustomsClearancePrice(productEasyExcel.getCustomsClearancePrice());
            product.setCustomsClearanceWeight(productEasyExcel.getCustomsClearanceWeight());
            product.setCustomsClearanceTexture(productEasyExcel.getCustomsClearanceTexture());
            product.setCustomsClearanceUse(productEasyExcel.getCustomsClearanceUse());
            product.setCustomsClearanceSn(productEasyExcel.getCustomsClearanceSn());
            product.setCustomsClearanceRisky(productEasyExcel.getCustomsClearanceRisky());
            product.setCategoryName(productEasyExcel.getCategoryName()); // 类目名称
            product.setProviderName(productEasyExcel.getProviderName()); // 供应商名称
            product.setAddTime(LocalDateTime.now());
            product.setUpdateTime(LocalDateTime.now());
            product.setDeleted(false);
            productList.add(product);
        }
        // 获取所有的类目
        List<Category> categoryList = easyExcelService.categoryService.selectAllEasyExcel();
        // 获取所有的供应商
        List<Provider> providerList = easyExcelService.providerService.selectAllEasyExcel();
        // 设置类目id
        for (Product product : productList) {
            for (Category category : categoryList) {
                if (product.getCategoryName().equals(category.getNameCn())) {
                    product.setCategoryId(category.getId());
                }
            }
        }
        // 设置供应商id
        for (Product product : productList) {
            for (Provider provider : providerList) {
                if (product.getProviderName().equals(provider.getProviderName())) {
                    product.setProviderId(provider.getId());
                }
            }
        }

        // 批量新增商品
        easyExcelService.productService.insertSelectiveList(productList);

        // 筛查存储到店铺商品表的信息 -->
        // 存储每个商品在那个店铺售卖的相关信息 key:productSku
        Map<String,List<StoreProductEasyExcel>> listMap = new HashMap<>();
        listMap.put("存储每个商品在那个店铺售卖的相关信息",new ArrayList<>());
        // -->
        // 遍历完之后listMap就会是：Map<单个商品的sku,List<多个店铺商品sku>>
        for (ProductEasyExcelGroupAdd productEasyExcel : list) {
            // 判断是否已经存在这个商品项
            for (Map.Entry entry : listMap.entrySet()) {
                if (entry.getKey().equals(productEasyExcel.getProductSku())) {
                    StoreProductEasyExcel storeProductEasyExcel = new StoreProductEasyExcel();
                    storeProductEasyExcel.setStoreName(productEasyExcel.getStoreName());
                    storeProductEasyExcel.setStoreProductSku(productEasyExcel.getStoreProductSku());
                    listMap.get(productEasyExcel.getProductSku()).add(storeProductEasyExcel);
                }
            }
            // 如果循环完没有这个商品就创建这个项
            if (listMap.get(productEasyExcel.getProductSku()) == null) {
                List<StoreProductEasyExcel> storeProductEasyExcels = new ArrayList<>();
                StoreProductEasyExcel storeProductEasyExcel = new StoreProductEasyExcel();
                storeProductEasyExcel.setStoreName(productEasyExcel.getStoreName());
                storeProductEasyExcel.setStoreProductSku(productEasyExcel.getStoreProductSku());
                storeProductEasyExcels.add(storeProductEasyExcel);
                listMap.put(productEasyExcel.getProductSku(), storeProductEasyExcels);
            }
        }
        // -->
        // storeProductSku productId storeId
        List<StoreProduct> storeProductList = new ArrayList<>();
        // 获取所有商品的id和sku,名称,图片
        List<Product> productListAllIdAndSku = easyExcelService.productService.selectListAll();
        // 匹配要添加到店铺商品表的基本信息（存放到集合中）
        for (Product product : productListAllIdAndSku) {
            for (Map.Entry entry : listMap.entrySet()) {
                if (product.getProductSku().equals(entry.getKey())) {
                    List<StoreProductEasyExcel> listOne = (List<StoreProductEasyExcel>)entry.getValue();
                    for (StoreProductEasyExcel storeProductEasyExcel : listOne) {
                        StoreProduct storeProduct = new StoreProduct();
                        storeProduct.setProductId(product.getId());
                        storeProduct.setStoreProductSku(storeProductEasyExcel.getStoreProductSku());
                        storeProduct.setStoreName(storeProductEasyExcel.getStoreName());
                        storeProduct.setAddTime(LocalDateTime.now());
                        storeProduct.setUpdateTime(LocalDateTime.now());
                        storeProduct.setDeleted(false);
                        storeProductList.add(storeProduct);
                    }
                }
            }
        }
        // 获取所有店铺id和名称
        List<Store> storeList = easyExcelService.storeService.selectListAllIdAndName();
        // 设置店铺id
        for (StoreProduct storeProduct : storeProductList) {
            for (Store store : storeList) {
                if (storeProduct.getStoreName().equals(store.getStoreName())) {
                    storeProduct.setStoreId(store.getId());
                }
            }
        }
        // 批量新增店铺商品
        easyExcelService.storeProductService.insertSelectiveList(storeProductList);

        // 筛查存储到组合商品表的信息 -->
        // 筛选商品sku Map<组合商品sku,单个商品sku 例如：[3B1238,3B1239,3B1240...]>
        // Map<String,String[]> map = new HashMap<>();
        // 批量新增组合商品需要字段： 商品id [商品sku] 商品名称 缩略图片 商品数量
        List<ProductGroup> productGroupList = new ArrayList<>();
        for (ProductEasyExcelGroupAdd productEasyExcelGroupAdd : productEasyExcelList) {
            String[] array = productEasyExcelGroupAdd.getProductGroupSku().split(",");
            for (String s : array) {
                ProductGroup productGroup  = new ProductGroup();
                productGroup.setProductParentSku(s);
                productGroup.setProductSkuGroup(productEasyExcelGroupAdd.getProductSku());
                productGroupList.add(productGroup);
            }
        }
        // 筛查存储到组合商品表的信息
        List<ProductGroup> productGroupListTwo = new ArrayList<>();
        for (Product product : productListAllIdAndSku) {
            for (ProductGroup productGroup : productGroupList) {
                if (product.getProductSku().equals(productGroup.getProductParentSku())) {
                    productGroup.setProductParentId(product.getId());
                    productGroup.setProductParentName(product.getProductNameCn());
                    productGroup.setProductParentPictures(product.getPictures());
                    productGroup.setProductParentCount(CheckoutUtil.TYPE_ONE);
                    productGroup.setAddTime(LocalDateTime.now());
                    productGroup.setUpdateTime(LocalDateTime.now());
                    productGroup.setDeleted(false);
                    productGroupListTwo.add(productGroup);
                }
            }
        }
        // 设置productId组合商品id
        List<ProductGroup> productGroupListThree = new ArrayList<>();
        for (Product product : productListAllIdAndSku) {
            for (ProductGroup productGroup : productGroupListTwo) {
                if (product.getProductSku().equals(productGroup.getProductSkuGroup())) {
                    productGroup.setProductId(product.getId());
                    productGroupListThree.add(productGroup);
                }
            }
        }
        // 批量新增组合商品
        easyExcelService.productGroupService.insertSelectiveList(productGroupListThree);

    }


    /**
     * 采购计划批量导入 【用户id(暂时写死)】
     * @param list
     */
    @Transactional(rollbackFor = Exception.class)
    void insertSelectiveProcurementPlanList(List<ProcurementPlanEasyExcelAdd> list) {
        // 校验sku是否存在
        List<String> listSku = new ArrayList<>();
        for (ProcurementPlanEasyExcelAdd productEasyExcelAdd : list) {
            listSku.add(productEasyExcelAdd.getProductSku());
        }
        // 不存在提示错误信息
        if (easyExcelService.productMapper.selectListBySKU(listSku, listSku.get(CheckoutUtil.TYPE_ZERO)).size() <= CheckoutUtil.TYPE_ZERO) {
            throw new BizException(ErrorEnum.ErrorCode.skuNot);
        }
        // 存储批量添加采购计划的信息
        List<ProcurementPlan> procurementPlanList = new ArrayList<>();
        // 设置批量添加采购计划的信息
        for (ProcurementPlanEasyExcelAdd productEasyExcel : list) {
            ProcurementPlan procurementPlan = new ProcurementPlan();
            procurementPlan.setProductSku(productEasyExcel.getProductSku());
            procurementPlan.setProcurementPlanCount(productEasyExcel.getProcurementPlanCount());
            procurementPlan.setProcurementPlanStore(productEasyExcel.getProcurementPlanStore());
            procurementPlan.setProcurementPlanDesc(productEasyExcel.getProcurementPlanDesc());
            procurementPlanList.add(procurementPlan);
        }
        // 获取商品信息
        List<Product> productList = easyExcelService.productService.selectListAll();
        // 设置类目id
        for (ProcurementPlan procurementPlan : procurementPlanList) {
            for (Product product : productList) {
                if (product.getProductSku().equals(procurementPlan.getProductSku())) {
                    procurementPlan.setProductId(product.getId());
                }
            }
        }
        Integer adminId = 1; // 用户id(暂时写死)
        // 批量新增商品
        easyExcelService.procurementPlanService.addList(adminId,procurementPlanList);
    }


    // 拆分字符串
    public static void main(String[] args) {
        String list = "3B1238,3B1239,3B1240";
        String[] chars = list.split(",");
        for (String aChar : chars) {
            System.out.println(aChar);
        }
    }

    /**
     * 批量修改商品(单个商品)
     * @param list
     */
    @Transactional(rollbackFor = Exception.class)
    void updateData(List<ProductEasyExcelUpdate> list) {
        // 存储批量添加商品的信息
        List<Product> productList = new ArrayList<>();
        // 设置批量添加商品基础信息
        for (ProductEasyExcelUpdate productEasyExcel : list) {
            Product product = new Product();
            product.setProductSku(productEasyExcel.getProductSku());
            product.setProductNameCn(productEasyExcel.getProductNameCn());
            product.setProductNameEn(productEasyExcel.getProductNameEn());
            product.setProductState(productEasyExcel.getProductState());
            product.setLength(productEasyExcel.getLength());
            product.setWidth(productEasyExcel.getWidth());
            product.setHeight(productEasyExcel.getHeight());
            product.setCubageWeight(productEasyExcel.getCubageWeight());
            product.setProductWeight(productEasyExcel.getProductWeight());
            product.setBoxNumber(productEasyExcel.getBoxNumber());
            product.setPurchasePrice(productEasyExcel.getPurchasePrice());
            product.setPictures(productEasyExcel.getPictures());
            product.setProductDesc(productEasyExcel.getProductDesc());
            product.setCustomsClearanceNameCn(productEasyExcel.getCustomsClearanceNameCn());
            product.setCustomsClearanceNameEn(productEasyExcel.getCustomsClearanceNameEn());
            product.setCustomsClearancePrice(productEasyExcel.getCustomsClearancePrice());
            product.setCustomsClearanceWeight(productEasyExcel.getCustomsClearanceWeight());
            product.setCustomsClearanceTexture(productEasyExcel.getCustomsClearanceTexture());
            product.setCustomsClearanceUse(productEasyExcel.getCustomsClearanceUse());
            product.setCustomsClearanceSn(productEasyExcel.getCustomsClearanceSn());
            product.setCustomsClearanceRisky(productEasyExcel.getCustomsClearanceRisky());
            product.setCategoryName(productEasyExcel.getCategoryName()); // 类目名称
            product.setProviderName(productEasyExcel.getProviderName()); // 供应商名称
            product.setUpdateTime(LocalDateTime.now());
            productList.add(product);
        }
        // 获取所有的类目
        List<Category> categoryList = easyExcelService.categoryService.selectAllEasyExcel();
        // 获取所有的供应商
        List<Provider> providerList = easyExcelService.providerService.selectAllEasyExcel();
        // 设置类目id
        for (Product product : productList) {
            for (Category category : categoryList) {
                if (product.getCategoryName().equals(category.getNameCn())) {
                    product.setCategoryId(category.getId());
                }
            }
        }
        // 设置供应商id
        for (Product product : productList) {
            for (Provider provider : providerList) {
                if (product.getProviderName().equals(provider.getProviderName())) {
                    product.setProviderId(provider.getId());
                }
            }
        }
        // 批量修改商品
        if (easyExcelService.productService.updateSelectiveList(productList) <= 0) {
            throw new BizException(ErrorEnum.ErrorCode.UpdateUnsuccessful);
        }
    }


}
